package com.ms.p2p.interceptor;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.utils.ResponseUtils;
import com.ms.p2p.entity.RetMap;
import com.ms.p2p.entity.UserThreadLocal;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.provider.MemberProvider;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class AppLoginInterceptor implements HandlerInterceptor {

    @Reference
    MemberProvider memberProvider;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        HashMap map = new HashMap();
        String member_id = request.getParameter("member_id");
        if(StringUtils.isBlank(member_id)){
            ResponseUtils.renderJSON(RetMap.Error("用户未登录"), response);
            return false;
        }
        //这里使用priciple更合适
        Member member =   memberProvider.findById(Integer.parseInt(member_id));
        if(member == null){
            map.put("status",0);
            map.put("message","用户未登录");
            ResponseUtils.renderJSON(RetMap.Error("用户未登录"), response);
            return false;
        }
        UserThreadLocal.set(member);//在后台不需要在获取一次
        return true;
    }


    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }


    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        clearCache(response);
    }


    /**
     * 清除缓存
     */
    private void clearCache(HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
    }

}
